//
//  XPStatusesRetweetView.swift
//  SinaWeibo
//
//  Created by 徐攀 on 16/5/13.
//  Copyright © 2016年 徐攀. All rights reserved.
//

import UIKit
import SnapKit

class XPStatusesRetweetView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var retweetViewBottom: Constraint?
    
    var statuses: XPStatusesCellViewModel? {
        didSet{
            let retweetName = statuses?.statuses?.user?.screen_name ?? ""
            let retweetContent = statuses?.statuses?.retweeted_status?.text ?? ""
            contentLabel.text = "@\(retweetName):\(retweetContent)"
            
            pictureView.countLabel.text = "\(statuses?.retweetPicCount ?? 0)"
            pictureView.picUrls = statuses?.statuses?.retweeted_status?.pic_urls
            
            updateSubviewsConstraints()
        }
    }
    
    private func updateSubviewsConstraints() {
        retweetViewBottom?.uninstall()
        if statuses?.retweetPicCount > 0 {
            pictureView.hidden = false
            snp_updateConstraints(closure: { (make) -> Void in
                self.retweetViewBottom = make.bottom.equalTo(pictureView).offset(commonMargin).constraint
            })
            pictureView.snp_updateConstraints(closure: { (make) -> Void in
                make.size.equalTo(pictureView.pictureViewSize(statuses?.retweetPicCount ?? 0))
            })
            
        } else {
            snp_updateConstraints(closure: { (make) -> Void in
                self.retweetViewBottom = make.bottom.equalTo(contentLabel).offset(commonMargin).constraint
            })
            pictureView.hidden = true
        }
    }
    
    // 懒加载控件
    private lazy var pictureView: XPPictureView = XPPictureView()
    private lazy var contentLabel: UILabel = {
        let label = UILabel(color: UIColor.darkTextColor(), fontSize: 14)
        label.numberOfLines = 0;
        return label
    }()
    
    private func setupUI() {
        backgroundColor = UIColor(white:0.98, alpha:1.0)
        
        addSubview(contentLabel)
        addSubview(pictureView)
        
        contentLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self).offset(commonMargin)
            make.leading.equalTo(self).offset(commonMargin)
            make.trailing.equalTo(self).offset(-commonMargin)
        }
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentLabel.snp_bottom).offset(commonMargin)
            make.leading.equalTo(contentLabel)
        }
        snp_makeConstraints { (make) -> Void in
            self.retweetViewBottom = make.bottom.equalTo(pictureView).offset(commonMargin).constraint
        }
    }
    
}
